package com.fhx.core.utils

import java.math.BigDecimal
import java.math.RoundingMode
import java.text.DecimalFormat

/**
 * author fhx
 * create time 2020/5/3 1:20
 **/
class PriceFormatUtil {
    companion object {
        /**
         * len 小数点长度(如果末尾0的话会省略)
         * 1.01200返回1.012
         * 1.00返回1
         */
        fun format(source: Double?, decimalNumber: Int): String {
//            val nf = NumberFormat.getNumberInstance()
//            nf.maximumFractionDigits = len
//            nf.roundingMode = RoundingMode.DOWN
//            //本来1234.456，会返回1,234.456  超过1000会带有逗号, 很多地方用这个值去转double了，会出异常
//            return nf.format(num).replace(",","")
            return if (decimalNumber <= 0) {
                "" + source?.toInt()
            } else {
                val sb = StringBuilder("#0.")
                for (i in 1..decimalNumber) {
                    sb.append("0")
                }

                var  a:String="0"
                val df = DecimalFormat(sb.toString())
                try {
                    df.roundingMode = RoundingMode.HALF_DOWN //为保持精度，舍弃后4小数
                    val decimalD: BigDecimal = BigDecimal.valueOf(source!!)

                    a =  df.format(decimalD)
                }catch (e :Exception){
                    val decimalD: BigDecimal = BigDecimal.valueOf(source!!)
                    a=df.format(decimalD)
                }
              a
            }
        }

        /**
         * 格式化小数点
         * 1转为1.00，后面会补0
         */
        fun formatNumber(source: Double?, decimalNumber: Int): String? {
            return if (decimalNumber <= 0) {
                "" + source?.toInt()
            } else {
                val sb = StringBuilder("#0.")
                for (i in 1..decimalNumber) {
                    sb.append("0")
                }
                var  a:String="0"
                val df = DecimalFormat(sb.toString())
                try {
                    df.roundingMode = RoundingMode.HALF_DOWN //为保持精度，舍弃后4小数
                    val decimalD: BigDecimal = BigDecimal.valueOf(source!!)
                    a =  df.format(decimalD)
                }catch (e :Exception){
                    val decimalD: BigDecimal = BigDecimal.valueOf(source!!)
                    a=df.format(decimalD)
                }
                a
            }
        }
    }


}